package com.example.springbootdemo.service.impl;

import com.example.springbootdemo.config.QiNiuConfig;
import com.example.springbootdemo.service.FileService;
import com.example.springbootdemo.util.QiniuUtil;
import com.google.gson.Gson;
import com.qiniu.common.QiniuException;
import com.qiniu.common.Zone;
import com.qiniu.http.Response;
import com.qiniu.storage.BucketManager;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.UploadManager;
import com.qiniu.storage.model.DefaultPutRet;
import com.qiniu.util.Auth;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;

@Slf4j
@Service
public class FileServiceImpl implements FileService {

    @Resource
    private QiNiuConfig qiNiuConfig;

    /**七牛文件上传管理器*/
    private UploadManager uploadManager;
    /**上传的token*/
    private String token;
    /**七牛认证管理*/
    private Auth auth;

    private BucketManager bucketManager;


    public FileServiceImpl(QiNiuConfig qiNiuConfig) {
        // 我是华东地区的所以是zone0，如果是其他地区的需要修改

        uploadManager = new UploadManager(new Configuration(Zone.autoZone()));
        auth = Auth.create(qiNiuConfig.getAccessKey(), qiNiuConfig.getSecretKey());
        // 根据命名空间生成的上传token
        token = auth.uploadToken(qiNiuConfig.getBucketName());
        bucketManager = new BucketManager(auth,new Configuration(Zone.autoZone()));
    }
    @Override
    public String uploadQNImg(MultipartFile file) {
        String resultImage = "失败";
        try {
            // 判断图片后缀，并使用工具类根据上传文件生成唯一图片名称,防止截断字符如“%00”
            String fileName = file.getOriginalFilename();
            String imgName = null;
            if (fileName != null) {
                imgName = QiniuUtil.getRandomImgName(fileName);
            }
            //判断是否为恶意程序
            //通过流的方式把文件转换为BufferedImage对象,获取宽和高,只有图片才具有宽高属性
            BufferedImage bufferedImage = ImageIO.read(file.getInputStream());
            if(bufferedImage == null || bufferedImage.getHeight()==0 || bufferedImage.getWidth()==0){
                return resultImage;
            }

            // 上传图片文件
            Response res = uploadManager.put(file.getInputStream(), imgName, token, null, null);
            if (!res.isOK()) {
                throw new RuntimeException("上传七牛出错：" + res.toString());
            }
            // 解析上传成功的结果
            DefaultPutRet putRet = new Gson().fromJson(res.bodyString(), DefaultPutRet.class);

            // 直接返回外链地址
            return getPrivateFile(imgName);
        } catch (Exception e) {
            log.error(e.toString());
        }
        return "失败";
    }

    @Override
    public Integer deleteImg(String imgUrl) {
        try {
            Response res = bucketManager.delete(qiNiuConfig.getBucketName(),imgUrl);
            if (!res.isOK()) {
                throw new RuntimeException("七牛删除出错：" + res.toString());
            }
            else {
                return 1;
            }
        } catch (QiniuException e) {
            throw new RuntimeException(e);
        }
    }

    public String getPrivateFile(String fileKey) {
        String encodedFileName = null;
        String finalUrl = null;
        try {
            encodedFileName = URLEncoder.encode(fileKey, "utf-8").replace("+", "%20");
            //1小时，可以自定义链接过期时间
//            long expireInSeconds = 3600;
//            finalUrl = auth.privateDownloadUrl(publicUrl, expireInSeconds);
            finalUrl = String.format("%s/%s", qiNiuConfig.getUrl(), encodedFileName);
        } catch (UnsupportedEncodingException e) {
            log.error(e.toString());
        }
        return finalUrl;
    }



}